﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Urb.Weather.Core;
using Urb.Weather.Core.Util;

namespace Urb.Weather.MSN.IntegrationTests
{
    [TestClass]
    public class GettingAndAnalyzingCurrentMSNWeatherRealData
    {
        private MSNResponseAnalyzer responseAnalyzer;

        private const int minServiceQueryInterval = 2000;
        private static DateTime? lastServiceQueryTime;

        [TestInitialize]
        public void TestInitialize()
        {
            responseAnalyzer = new MSNResponseAnalyzer();
        }
        
        [TestMethod]
        public void YahooWeather_Wroclaw_CurrentConditions_enUSCulture()
        {
            // wc:PLXX0029 - Wroclaw
            CurrentConditions("wc:PLXX0029", "en-US");
        }

        [TestMethod]
        public void YahooWeather_Wroclaw_CurrentConditions_plPLCulture()
        {
            // wc:PLXX0029 - Wroclaw
            CurrentConditions("wc:PLXX0029", "pl-PL");
        }

        [TestMethod]
        public void YahooWeather_Wroclaw_CurrentConditions_NoCulture()
        {
            // wc:PLXX0029 - Wroclaw
            CurrentConditions("wc:PLXX0029");
        }

        [TestMethod]
        public void YahooWeather_CurrentConditions_NoLocationNoCulture()
        {
            CurrentConditions();
        }

        private void CurrentConditions(string locationCode = null, string culture = null)
        {
            if (lastServiceQueryTime.HasValue && (DateTime.Now - lastServiceQueryTime.Value).TotalMilliseconds < minServiceQueryInterval)
                Thread.Sleep(minServiceQueryInterval);

            lastServiceQueryTime = DateTime.Now;

            MSNWeatherUri uri = new MSNWeatherUri(locationCode, culture);

            string response = new WebClient().DownloadString(uri.ToString());
            
            Assert.IsNotNull(response);
            Assert.IsTrue(response.Length > 0);

            MSNWeatherData weatherData = responseAnalyzer.Analyze(response);

            Assert.IsTrue(
                EqualityChecker.AreAllFieldsNotNull<MSNWeatherData>(weatherData)
                );

            Assert.IsTrue(weatherData.Forecasts.Count > 0);

            Assert.IsTrue(
                EqualityChecker.AreAllCollectionElementFieldsNotNull<MSNWeatherForecastData>(weatherData.Forecasts)
                );

            Assert.AreEqual(response, weatherData.SourceXml);
        }
    }
}
